package com.linking.config.pojo;

import java.util.Map;
import lombok.Data;
import org.yaml.snakeyaml.Yaml;

/**
 * @Author YaoWeiXin
 * @Date 2019/12/5 15:46
 * @Description 启动配置参数
 */
@Data
public class BootstrapConfigBO {

  private String nacosAddr;
  private String appDataId;
  private String appGroup;
  private Integer workerId;
  private String prefixUrl;
  private Boolean countJob;

  public static BootstrapConfigBO of(String nacosAddr, String appDataId, String appGroup,
      Integer workerId, String prefixUrl) {
    return of(nacosAddr, appDataId, appGroup, workerId, prefixUrl, false);
  }

  public static BootstrapConfigBO of(String nacosAddr, String appDataId, String appGroup,
      Integer workerId, String prefixUrl, Boolean isCountJob) {
    BootstrapConfigBO bo = new BootstrapConfigBO();
    bo.setNacosAddr(nacosAddr);
    bo.setAppDataId(appDataId);
    bo.setAppGroup(appGroup);
    bo.setWorkerId(workerId);
    bo.setPrefixUrl(prefixUrl);
    bo.setCountJob(isCountJob);
    return bo;
  }

  public static BootstrapConfigBO of(String param) {
    Yaml yaml = new Yaml();
    Map config = yaml.load(param);
    Map nacosConfig = (Map) ((Map) ((Map) ((Map) config.get("spring")).get("cloud")).get("nacos"))
        .get("config");
    Map applicationConfig = (Map) ((Map) config.get("spring")).get("application");
    String nacosAddr = (String) nacosConfig.get("server-addr");
    String dataId = (String) applicationConfig.get("name");
    String groupId = (String) nacosConfig.get("group");
    int workerId = config.containsKey("worker-id") ? (Integer) config.get("worker-id") : 0;
    String prefixUrl = config.containsKey("prefix_url") ? (String) config.get("prefix_url") : "/s/";
    boolean isCountJob = config.containsKey("is-count-job") ? (Boolean) config.get("is-count-job") : false;
    return of(nacosAddr, dataId, groupId, workerId, prefixUrl, isCountJob);
  }
}
